package com.itext.sample.util;


import com.itextpdf.awt.geom.AffineTransform;
import com.itextpdf.awt.geom.Rectangle2D;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class PdfUtils {


    public static void stampImage(String sourcePath, String targetPath, String imagePath, Set<String> keyWords) throws Exception {

        // 初始化输入输出流
        // 源PDF文件
        PdfReader pdfReader = new PdfReader(sourcePath);
        // 目标文件
        FileOutputStream fout = new FileOutputStream(targetPath);
        // 写目标文件
        PdfStamper pdfStamper = new PdfStamper(pdfReader, fout);

//        Image image = getImage(imagePath);

        List<MatchCoordinate> coordinateList = getKeyWords(pdfReader, pdfStamper, imagePath, keyWords);

        System.out.println("coordinateList's size : " + coordinateList.size());

        // 将输入输出流关闭
        pdfStamper.close();
        fout.close();
        pdfReader.close();
    }

    private static Image getImage(String imagePath) throws BadElementException, IOException {
        // 读取印章图片，并缩放
        Image image = Image.getInstance(imagePath);
        image.scaleAbsolute(150f, 150f);
        return image;
    }


    /**
     * @param pdfReader
     * @param keyWords
     * @return List<Coordinate>
     * @Author AlphaJunS
     * @Date 18:26 2020/3/7
     * @Description 获取关键字所在PDF坐标
     */
    public static List<MatchCoordinate> getKeyWords(PdfReader pdfReader, PdfStamper pdfStamper, String imagePath, Set<String> keyWords) throws Exception {
        List<MatchCoordinate> coordinateList = new ArrayList<>();
        int pageNum = pdfReader.getNumberOfPages();
        PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
        CustomRenderListener renderListener = new CustomRenderListener();
        for (int page = 1; page <= pageNum; page++) {
            for (String keyWrod : keyWords) {
                renderListener.setKeyWord(keyWrod);
                renderListener.setPage(page);
                pdfReaderContentParser.processContent(page, renderListener);
                MatchCoordinate coordinate = renderListener.getCoordinate();
                if (coordinate != null) {
                    coordinateList.add(coordinate);
                    // 设置图片水印的位置
                    Image image = getImage(imagePath);
                    image.setAbsolutePosition(coordinate.getX(), coordinate.getY());
                    // 开始水印 如果需要每一页都加图片
                    // PdfContentByte pdfContentByte = pdfStamper.getOverContent(page);
                    pdfStamper.getOverContent(page).addImage(image);
                }
            }
        }
        return coordinateList;
    }


    /**
     * @Author AlphaJunS
     * @Date 12:53 2020/3/7
     * @Description pdf签名帮助类
     */
    public static class CustomRenderListener implements RenderListener {

        private String keyWord;

        private int page;

        private MatchCoordinate coordinate;

        public int getPage() {
            return page;
        }

        public void setPage(int page) {
            this.page = page;
        }

        public MatchCoordinate getCoordinate() {
            return coordinate;
        }

        public String getKeyWord() {
            return keyWord;
        }

        public void setKeyWord(String keyWord) {
            this.keyWord = keyWord;
        }

        @Override
        public void beginTextBlock() {
        }

        @Override
        public void endTextBlock() {
        }

        @Override
        public void renderImage(ImageRenderInfo arg0) {
        }

        @Override
        public void renderText(TextRenderInfo textRenderInfo) {
            String text = textRenderInfo.getText();
            if (null != text && text.contains(keyWord)) {
                Rectangle2D.Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange();
                coordinate = new MatchCoordinate(keyWord, page, boundingRectange.x, boundingRectange.y);
            }
        }

    }


    public static class MatchCoordinate {

        private String keyWord;
        private int page;
        private float x;
        private float y;

        public MatchCoordinate(String keyWord, int page, float x, float y) {
            this.keyWord = keyWord;
            this.page = page;
            this.x = x;
            this.y = y;
        }

        public String getKeyWord() {
            return keyWord;
        }

        public void setKeyWord(String keyWord) {
            this.keyWord = keyWord;
        }

        public int getPage() {
            return page;
        }

        public void setPage(int page) {
            this.page = page;
        }

        public float getX() {
            return x;
        }

        public void setX(float x) {
            this.x = x;
        }

        public float getY() {
            return y;
        }

        public void setY(float y) {
            this.y = y;
        }
    }

}
